<template>
  <main-header />
  <app-center />
  <div style="width: calc(100% - 80px)">
    <main-content
      title="商城管理"
      style="padding-top: 60px; left: 60px; position: relative"
    >
      <template
        v-if="mallList.length"
        #actions-bar
      >
        <el-button
          v-has="['08010101']"
          type="primary"
          @click="showAddMall"
        >
          新增商城
        </el-button>
      </template>

      <div
        v-loading="loading"
        class="page-content"
      >
        <div
          v-if="!mallList.length"
          class="create-mall"
        >
          <div class="icon">
            <el-image :src="PointsMall" />
          </div>
          <div class="title">
            您还未创建商城
          </div>
          <div class="description">
            您还未创建属于自己的商城
          </div>
          <div class="description">
            请去创建属于自己的商城吧~
          </div>
          <el-button
            v-has="['08010101']"
            style="margin-top: 21px"
            type="primary"
            @click="showAddMall"
          >
            <el-icon>
              <Plus />
            </el-icon> 立即创建
          </el-button>
        </div>

        <div
          v-else
          class="mall-list-wrapper"
        >
          <div
            v-for="(item, index) in mallList"
            :key="index"
            class="mall-card"
          >
            <div class="img-wrapper">
              <img
                v-if="item.homePageId"
                class="mall-img"
                :src="item.homePageImg"
                alt="积分商城图标"
              >
              <div
                v-else
                class="mall-empty-img"
              >
                <img
                  :src="MallIcon"
                  alt="积分商城图标"
                >
                <p>还未配置商城首页</p>
              </div>
            
              <div class="page-card-overlay">
                <div
                  class="preview-button"
                  @click="promote(item.mallCode)"
                >
                  预览
                </div>
                <div
                  class="preview-button"
                  @click="goHome(item, <number>index)"
                >
                  进入商城
                </div>
              </div>
            </div>
            <div
              class="mall-info"
              @click="goHome(item, <number>index)"
            >
              <div class="mall-name">
                <div class="mall-currency">
                  {{ getCurrencyLabel(item.currencyId) }}
                </div>
                <div class="mall-name-mall">
                  <el-tooltip
                    effect="dark"
                    :content="item.mallName"
                    placement="top-start"
                  >
                    {{ item.mallName }}
                  </el-tooltip>
                </div>
              </div>
              <div class="mall-type">
                <p>创建于{{ formatTime(item.createTime) }}</p>
                <p v-if=" item.createUserName">{{ item.createUserName }}  创建</p> 
              </div>
            </div>
          </div>
        </div>
      </div>

      <el-dialog
        v-model="isShowAddMall"
        title="新建商城"
        destroy-on-close
      >
        <el-form
          ref="addMallFormRef"
          :model="addMallForm"
          :rules="addMallFormRules"
          :label-width="90"
        >
          <el-form-item
            prop="mallName"
            label="商城名称"
          >
            <el-input
              v-model="addMallForm.mallName"
              placeholder="请输入商城名称"
              maxlength="15"
              show-word-limit
            />
          </el-form-item>

          <el-form-item
            prop="currencyId"
            label="积分类型"
          >
            <el-radio-group
              v-if="currencyTypes.length"
              v-model="addMallForm.currencyId"
            >
              <el-radio
                v-for="(item, index) in currencyTypes"
                :key="index"
                :label="item.id"
              >
                {{ item.name }}
              </el-radio>
            </el-radio-group>
            <span v-else>
              尚未创建积分类型，前往
              <span
                class="highlight-href"
                @click="goTokensManage"
              >创建</span>
              （已创建？<span
                class="highlight-href"
                @click="getCurrencyTypes"
              >点击刷新</span>）
            </span>
          </el-form-item>

          <el-form-item
            prop="payConfigId"
            label="支付配置"
          >
            <!-- <el-select
              v-model="addMallForm.payConfigId"
              placeholder="请选择支付配置"
              @change="setPayType"
            >
              <el-option
                v-for="item in payConfigList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select> -->
            <ScSelector
              v-model="addMallForm.payConfigId"
              placeholder="请选择支付配置"
              type="config"
              :params="{ attach: 'pay' }"
              @change-selected="setPayType"
            >
              <template #expand-pop="{ data }">
                <div
                  v-if="data"
                  class="detail-container"
                >
                  <div class="detail-text">
                    <h3>
                      {{ data.info.name }}
                    </h3>
                  </div>
                  <div class="detail-text_line">
                    配置类型：{{ data.info.externalTypeName }}
                  </div>
                  <div class="detail-text_line">
                    所属平台：{{ data.info.externalPlatformTypeName }}
                  </div>
                  <div class="detail-text_line">
                    配置标识：{{ data.info.unique }}
                  </div>
                  <div class="detail-text_line">
                    描述：{{ data.info.remark || "暂无" }}
                  </div>
                </div>
              </template>
            </ScSelector>
          </el-form-item>

          <el-form-item
            prop="payConfigId"
            label="会员配置"
          >
            <ScSelector
              v-model="addMallForm.externalMemberConfigId"
              placeholder="请选择会员配置"
              type="config"
              :params="{ attach: 'member' }"
              @change-selected="setPayType"
            >
              <template #expand-pop="{ data }">
                <div
                  v-if="data"
                  class="detail-container"
                >
                  <div class="detail-text">
                    <h3>
                      {{ data.info.name }}
                    </h3>
                  </div>
                  <div class="detail-text_line">
                    配置类型：{{ data.info.externalTypeName }}
                  </div>
                  <div class="detail-text_line">
                    所属平台：{{ data.info.externalPlatformTypeName }}
                  </div>
                  <div class="detail-text_line">
                    配置标识：{{ data.info.unique }}
                  </div>
                  <div class="detail-text_line">
                    描述：{{ data.info.remark || "暂无" }}
                  </div>
                </div>
              </template>
            </ScSelector>
          </el-form-item>

          <el-form-item
            prop="loginType"
            label="登录方式"
          >
            <el-radio-group v-model="addMallForm.loginType">
              <el-radio label="sms">
                手机号码登录
              </el-radio>
              <el-radio label="external">
                外部授权登录
              </el-radio>
            </el-radio-group>

            <el-form-item
              v-if="addMallForm.loginType == 'external'"
              label-width="20px"
              prop="externalLoginConfigId"
            >
              <ScSelector
                v-model="addMallForm.externalLoginConfigId"
                placeholder="请选择登录页"
                type="config"
                :params="{ attach: 'userLogin' }"
              >
                <template #expand-pop="{ data }">
                  <div
                    v-if="data"
                    class="detail-container"
                  >
                    <div class="detail-text">
                      <h3>
                        {{ data.info.name }}
                      </h3>
                    </div>
                    <div class="detail-text_line">
                      配置类型：{{ data.info.externalTypeName }}
                    </div>
                    <div class="detail-text_line">
                      所属平台：{{ data.info.externalPlatformTypeName }}
                    </div>
                    <div class="detail-text_line">
                      配置标识：{{ data.info.unique }}
                    </div>
                    <div class="detail-text_line">
                      描述：{{ data.info.remark || "暂无" }}
                    </div>
                  </div>
                </template>
              </ScSelector>
            </el-form-item>
          </el-form-item>

          <template v-if="addMallForm.loginType == 'sms'">
            <el-form-item
              label="登录页面"
              prop="loginStyleId"
            >
              <el-radio-group v-model="loginStyleIdModel">
                <el-radio :label="-1">
                  系统默认
                </el-radio>
                <el-radio :label="-2">
                  自定义
                </el-radio>
              </el-radio-group>
              <el-form-item
                v-if="loginStyleIdModel !== -1"
                label-width="20px"
                prop="loginStyleId"
              >
                <ScSelector
                  v-model="addMallForm.loginStyleId"
                  placeholder="请选择登录页"
                  type="loginStyle"
                  :params="{}"
                >
                  <template #expand-pop="{ data }">
                    <div
                      v-if="data"
                      class="detail-container"
                    >
                      <div class="detail-text">
                        <h3>
                          {{ data.info.title }}
                        </h3>
                      </div>
                      <el-image
                        style="width: 180px; height: 230px"
                        :src="data.info.cover"
                        fit="fill"
                      />
                    </div>
                  </template>
                </ScSelector>
              </el-form-item>
            </el-form-item>
          </template>

          <template v-if="addMallForm.loginType == 'sms'">
            <el-form-item
              prop="externalSmsConfigId"
              label="短信配置"
            >
              <el-radio-group v-model="externalSmsConfigIdModel">
                <el-radio :label="-1">
                  系统默认
                </el-radio>
                <el-radio :label="-2">
                  自定义
                </el-radio>
              </el-radio-group>
              <el-form-item
                v-if="externalSmsConfigIdModel !== -1"
                label-width="20px"
                prop="externalSmsConfigId"
              >
                <ScSelector
                  v-model="addMallForm.externalSmsConfigId"
                  placeholder="请选择验证码"
                  type="config"
                  :params="{ attach: 'sms_code' }"
                >
                  <template #expand-pop="{ data }">
                    <div
                      v-if="data"
                      class="detail-container"
                    >
                      <div class="detail-text">
                        <h3>
                          {{ data.info.name }}
                        </h3>
                      </div>
                      <div class="detail-text_line">
                        配置类型：{{ data.info.externalTypeName }}
                      </div>
                      <div class="detail-text_line">
                        所属平台：{{ data.info.externalPlatformTypeName }}
                      </div>
                      <div class="detail-text_line">
                        配置标识：{{ data.info.unique }}
                      </div>
                      <div class="detail-text_line">
                        描述：{{ data.info.remark || "暂无" }}
                      </div>
                    </div>
                  </template>
                </ScSelector>
              </el-form-item>
            </el-form-item>
          </template>
        </el-form>
        <template #footer>
          <el-button @click="showAddMall">
            取消
          </el-button>
          <el-button
            type="primary"
            @click="_createMall"
          >
            确定
          </el-button>
        </template>
      </el-dialog>

      <Dialog
        :model-value="promoteVisible"
        title="扫码预览"
        :width="500"
        @close="promoteVisible = false"
      >
        <div class="qrcode-container">
          <qrcode-vue
            :value="pageLink"
            :size="200"
            level="H"
          />
          <div class="tips">
            <div>手机扫左边二维码预览</div>
            <div>
              你也可以打开
              <a
                :href="pageLink"
                target="_blank"
              >新窗口预览</a>
            </div>
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <!-- <el-button
          v-clipboard="`${link}`"
          v-clipboard:success="clipboardSuccess"
          >复制链接</el-button
        > -->
            <el-button @click="copyItemUrl">复制链接</el-button>
            <el-button
              type="primary"
              @click="promoteVisible = false"
            >关闭</el-button>
          </span>
        </template>
      </Dialog>
    </main-content>
  </div>
</template>
<script lang="ts">
export default {
  name: "MallManageList",
};
</script>
<script setup lang="ts">
import type { FormInstance, FormRules } from "element-plus";
import { Ref, UnwrapRef } from "vue";
import { ElMessage } from "element-plus";

import { createMall, getMallList, getPreviewUrl } from "@/api/pointsMall";
import { ICreateMallData, IMallPageItem } from "@/api/modules/pointsMall";
import sysConfigApi from "@/api/sysConfigApi";

import { useGetCurrencyType } from "@/views/pointsMall/compositions/useGetCurrencyType";
import PointsMall from "@/assets/pointsMall/pm-listholder.png";
import MallIcon from "@/assets/pointsMall/empty.png";
import QrcodeVue from "qrcode.vue";
import moment from "moment";


const router = useRouter();
const store = useStore();
const previewPath = `${(window as any).VUE_APP_URL[import.meta.env.MODE].appPreviewPath
}${store.state.user.merchant.merchantCode}`;
const addMallFormRef = ref<FormInstance>();
const mallList: Ref<IMallPageItem[]> = ref([]);
const payConfigList = ref([] as any);
const loading = ref(false);
const _getMallList = async () => {
  loading.value = true;
  const rs = await getMallList();
  loading.value = false;
  mallList.value = rs.payload ?? [];
};

const isShowAddMall = ref(false);
const showAddMall = () => {
  isShowAddMall.value = !isShowAddMall.value;
};
const addMallForm: UnwrapRef<ICreateMallData> = reactive({
  mallName: "",
  payConfigId: "",
  payType: "",
  currencyId: null,
  externalMemberConfigId: "",
  loginType: "sms",
  externalLoginConfigId: null,
  loginStyleId: -1,
  // loginStyleIdSel: null,
  externalSmsConfigId: -1,
  // externalSmsConfigIdSel: -1,
});
const addMallFormRules: UnwrapRef<FormRules> = reactive({
  mallName: [
    {
      required: true,
      message: "请输入商城名称",
      trigger: "blur",
    },
  ],
  payConfigId: [
    {
      required: false,
      message: "请选择支付配置",
      trigger: "change",
    },
  ],
  currencyId: [
    {
      required: true,
      message: "请选择积分类型",
      trigger: "change",
    },
  ],
  loginType: [ { required: true, message: "请选择登录方式", trigger: "change" } ],
  loginStyleId: [ { required: true, message: "请选择配置", trigger: "change" } ],
  externalSmsConfigId: [ { required: true, message: "请选择配置", trigger: "change" } ],
  externalLoginConfigId: [ { required: true, message: "请选择配置", trigger: "change" } ],
});
const { currencyTypes, getCurrencyLabel, getCurrencyTypes } =
  useGetCurrencyType();
const _createMall = () => {
  addMallFormRef.value?.validate(async (valid, fields) => {
    if (valid) {
      const rs = await createMall(addMallForm);

      if (rs.code === 200) {
        ElMessage.success("创建成功");
        isShowAddMall.value = false;
        resetMallForm();
        _getMallList();
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

const formatTime = (val: number) => {
  return moment(val).format('YYYY-MM-DD HH:mm:ss')
}
const resetMallForm = () => {
  addMallForm.mallName = "";
  addMallForm.currencyId = null;
};
// 设置支付平台
const setPayType = (val: any) => {
  let externalPlatformType = val.selected[0].info.externalPlatformType;
  addMallForm.payType = externalPlatformType;
};

// 获取支付配置
const getConfigList = async () => {
  if (payConfigList.value.length) {
    return;
  }
  let rs: any = await sysConfigApi.getConfigList({ externalType: "pay" });
  if (rs.code == 200) {
    payConfigList.value = rs.payload;
  }
};

const loginStyleIdModel: Ref<number> = ref(-1);
watch(loginStyleIdModel, (newVal) => {
  if (newVal === -1) { // 系统默认
    addMallForm.loginStyleId = -1
  }
})

const externalSmsConfigIdModel: Ref<number> = ref(-1);
watch(externalSmsConfigIdModel, (newVal) => {
  if (newVal === -1) { // 系统默认
    addMallForm.externalSmsConfigId = -1
  }
})

const goHome = (item: IMallPageItem, index: number) => {
  store.commit("pointsMall/updateMallConfig", item);

  store.commit("SETBOOKLIST", {
    path: "/mall/decorate/page",
    service: store.state.user.currentService,
  });
  router.push("/mall/decorate/page");
};

const goTokensManage = () => {
  window.open(`${location.origin}/merchant/#/merchant/tokens/tokensManage`);
};
const pageLink = ref("")
const promoteVisible = ref(false);
const promote = async (id:number) => {
  pageLink.value = `${previewPath}#/mall/${id}`
  promoteVisible.value = true;
};
const copyItemUrl = () => {
  let oInput = document.createElement("input");
  // 将想要复制的值
  oInput.value = pageLink.value;
  // 页面底部追加输入框
  document.body.appendChild(oInput);
  // 选中输入框
  oInput.select();
  // 执行浏览器复制命令
  document.execCommand("Copy");
  // 复制后移除输入框
  ElMessage({
    showClose: true,
    message: "复制成功",
    type: "success",
  });
  oInput.remove();
};
// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  () => {
    _getMallList()
  },
  {
    deep: true
  }
)
onMounted(() => {
  _getMallList();
  // getConfigList();
});
</script>

<style scoped lang="scss">
.page-content {
  min-height: 500px;
}

.create-mall {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);

  .title {
    color: rgba(44, 49, 59, 1);
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 8px;
  }

  .description {
    color: rgba(144, 147, 153, 1);
    font-size: 14px;
  }
}

.mall-list-wrapper {
  padding: 10px;
  min-width: 800px;
  height: 600px;
  display: flex;
  align-items: center;
  flex-shrink: 0;
  flex-grow: 1;
  flex-wrap: wrap;
  .mall-card {
    width: 265px;
    height: 382px;
    background: #FFFFFF;
    box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.09);
    border-radius: 8px;
    // width: 265px;
    // //height: 156px;
    // background: url("../../assets/pointsMall/pm-mall-bg.png") center/100% no-repeat;

    // border-radius: 4px;
    // box-shadow: 0 0 12px 0 rgba(0, 0, 0, 0.1);
    // padding: 20px;
    // transition: box-shadow 300ms linear;
    // cursor: pointer;
    // float: left;
    margin-bottom: 20px;
    margin-right: 20px;
    // clear: right;
   .img-wrapper{
      width: 265px;
      height: 280px;
      display: block;
      position: relative;
    .mall-img {
      object-fit: cover;
      object-position: top center;
      width: 100%;
      height: 100%;
    }
  
    .mall-empty-img {
      width: 265px;
      height: 280px;
      overflow: hidden;
      background: #F7F7F7;
border-radius: 8px 8px 0px 0px;
      img{
        width: 124px;
        height:102px;
        display: block;
        margin:69px auto 12px;
      }
      p{
        height: 21px;
        font-size: 15px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #666666;
        line-height: 21px;
        text-align: center;
      }
    }
    .page-card-overlay{
      width: 100%;
      height: 280px;
      position: absolute;
      top: 0;
      left: 0;
      background: rgba(0, 0, 0, 0.45);
      color: white;
      font-size: 14px;
      visibility: hidden;
      z-index: -1;
      opacity: 0;
      transition: opacity 200ms ease-in;
    }
    &:hover{
      .page-card-overlay{
        z-index: 1;
        visibility: visible;
        opacity: 1;
      }
    }
    .preview-button {
      margin:110px auto 20px;
      width: 130px;
      border-top: dashed 1px rgb(255, 255, 255);
      border-bottom: dashed 1px rgb(255, 255, 255);
      border-left: solid 1px rgb(255, 255, 255);
      border-right: solid 1px rgb(255, 255, 255);
      height: 36px;
      position: relative;
      border-radius: 18px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      color: #333;
      background-color: #fff;
      &:nth-of-type(2){
        margin-top: 0;
      }
    }
   }


    .mall-info {
      height: 102px;
      padding:12px;
      box-sizing: border-box;
      // flex: 1;
      // margin-left: 10px;
      .mall-name{
        display: flex;
        height:40px;
        align-items: center;
        .mall-currency{
          height: 20px;
          background: #FAAD14;
          border-radius: 2px;
          height: 20px;
          font-size: 14px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #FFFFFF;
          line-height: 20px;
          margin-right:5px;
          text-align: center;
          padding:0 3px;
          box-sizing: border-box;
        }
        .mall-name-mall{
          max-width: 195px;
          height: 20px;
          font-size: 15px;
          font-family: PingFangSC-Medium, PingFang SC;
          font-weight: 500;
          color: #333333;
          line-height: 21px;
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
        }
      }
    }

    .mall-type {
      color: rgba(134, 144, 156, 1);
      font-size: 14px;
    }
  }

  .mall-card:hover {
    box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0.2);
  }

  .mall-card:active {
    box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0.3);
  }
}

.el-select {
  width: 100%;
}

.highlight-href {
  color: var(--el-color-primary);
  cursor: pointer;
}

.detail-container {
  .detail-text_line {
    white-space: nowrap;
  }
}
.qrcode-container {
  display: flex;
  align-items: center;
  justify-content: center;

  .tips {
    color: #666666;
    margin-left: 20px;
    font-size: 14px;

    div {
      &+div {
        margin-top: 10px;
      }
    }

    a {
      color: var(--el-color-primary);
    }
  }
}
</style>
